/**
 * @Author: lianghuan
 * @Description: database
 * @emoji - ( ゜- ゜)つロ 乾杯~
 * @email lianghuanA@outlook.com
 * @Date: 2021-10-12 10:42
 * @Version: 1.0.0
 */

package common

import (
	"fmt"
	"github.com/spf13/viper"
	"go-gin/model"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var DB *gorm.DB

func InitDB() *gorm.DB {
	host := viper.GetString("datasource.host")
	port := viper.GetString("datasource.port")
	database := viper.GetString("datasource.database")
	username := viper.GetString("datasource.username")
	password := viper.GetString("datasource.password")
	charset := viper.GetString("datasource.charset")

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=true",
		username, password, host, port, database, charset)

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("failed to connect database, err: " + err.Error())
	}
	er := db.AutoMigrate(&model.User{})
	if er != nil {
		return nil
	}
	DB = db
	return db
}

func GetDB() *gorm.DB {
	return DB
}

func main() {
	InitDB()
}
